<template>
    <div class="search-page">
      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :model="searchForm" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="关键词">
                <el-input v-model="searchForm.keyword" placeholder="请输入商品名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="品牌">
                <el-input v-model="searchForm.brand" placeholder="请输入品牌"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="类别">
                <el-select v-model="searchForm.type" placeholder="请选择商品类别" clearable>
                  <el-option
                    v-for="item in productTypes"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="价格区间">
                <el-input-number v-model="searchForm.minPrice" :min="0" :precision="2" controls-position="right"></el-input-number>
                <span style="margin: 0 10px">-</span>
                <el-input-number v-model="searchForm.maxPrice" :min="0" :precision="2" controls-position="right"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" style="text-align: right">
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
  
      <!-- 搜索结果 -->
      <div class="search-results">
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="6" animated />
        </div>
        
        <template v-else>
          <div class="result-count">共找到 {{ total }} 件商品</div>
          
          <div v-if="productList.length === 0" class="empty-result">
            <el-empty description="没有找到符合条件的商品"></el-empty>
          </div>
          
          <el-row :gutter="20" v-else>
            <el-col :span="6" v-for="product in productList" :key="product.id">
              <el-card :body-style="{ padding: '0px' }" shadow="hover" class="product-card">
                <div class="product-image" @click="goToDetail(product.id)">
                  <el-image 
                    :src="product.productMainImg" 
                    fit="cover"
                    :preview-src-list="[product.mainImage]"
                    style="width: 100%; height: 200px">
                    <template #error>
                      <div class="image-error">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </div>
                <div style="padding: 14px;">
                  <div class="product-name" @click="goToDetail(product.id)">{{ product.productName }}</div>
                  <div class="product-brand">{{ product.productBrand }}</div>
                  <div class="product-price">
                    <span class="current-price">¥{{ product.productPrice}}</span>
                    <span v-if="product.originalPrice" class="original-price">¥{{ (product.productPrice * 1.2).toFixed(2) }}</span>
                  </div>
                  <div class="product-actions">
                    <el-button type="primary" size="small" @click="addToCart(product)">加入购物车</el-button>
                    <el-button size="small" @click="quickBuy(product)">立即购买</el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          
          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="searchForm.pageNum"
              v-model:page-size="searchForm.pageSize"
              :total="total"
              :page-sizes="[8, 16, 24, 32]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </template>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { Picture } from '@element-plus/icons-vue'
  import { productAPI } from '@/http'
  import { ElMessage } from 'element-plus'
  
  const router = useRouter()
  
  // 搜索表单数据
  const searchForm = ref({
    keyword: '',
    brand: '',
    type: '',
    minPrice: 0,
    maxPrice: 99999,
    pageNum: 1,
    pageSize: 8
  })
  
  // 商品类别选项
  const productTypes = ref([
    { value: 'electronics', label: '手机' },
    { value: 'clothing', label: '平板' },
    { value: 'food', label: '相机' },
    { value: 'books', label: '手表' },
    { value: 'home', label: '电子书' }
  ])
  
  // 商品列表数据
  const productList = ref([])
  const total = ref(0)
  const loading = ref(false)
  
  // 获取商品列表
  const fetchProductList = async () => {
    try {
      loading.value = true
      console.log(searchForm.value)
      const response = await productAPI.getProductListByCondition(searchForm.value)
      console.log('获取商品列表成功:', response)
      productList.value = response.data || []
      total.value = response.data.total || 0

      console.log('商品列表:', productList.value)
    } catch (error) {
      ElMessage.error('获取商品列表失败: ' + (error.message || '未知错误'))
      console.error('获取商品列表失败:', error)
    } finally {
      loading.value = false
    }
  }
  
  // 搜索按钮事件
  const handleSearch = () => {
    searchForm.value.pageNum = 1 // 重置页码
    fetchProductList()
  }
  
  // 重置搜索条件
  const resetSearch = () => {
    searchForm.value = {
      keyword: '',
      brand: '',
      type: '',
      minPrice: 0,
      maxPrice: 99999,
      pageNum: 1,
      pageSize: 8
    }
    fetchProductList()
  }
  
  // 分页大小改变
  const handleSizeChange = (val) => {
    searchForm.value.pageSize = val
    fetchProductList()
  }
  
  // 当前页改变
  const handleCurrentChange = (val) => {
    searchForm.value.pageNum = val
    fetchProductList()
  }
  
  // 跳转到商品详情
  const goToDetail = (productId) => {
    router.push({ name: 'ProductDetail', params: { id: productId } })
  }
  
  // 加入购物车
  const addToCart = (product) => {
    // 这里调用购物车API
    ElMessage.success(`${product.name} 已加入购物车`)
  }
  
  // 立即购买
  const quickBuy = (product) => {
    // 这里跳转到结算页面
    router.push({ 
      name: 'Checkout', 
      query: { 
        productId: product.id,
        quantity: 1
      }
    })
  }
  
  // 初始化加载
  onMounted(() => {
    // 从路由参数中获取初始搜索条件
    const route = router.currentRoute.value
    if (route.query.keyword) {
      searchForm.value.keyword = route.query.keyword
    }
    
    fetchProductList()
  })
  </script>
  
  <style scoped>
  .search-page {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .search-form {
    background-color: #fff;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .search-results {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .result-count {
    margin-bottom: 20px;
    font-size: 14px;
    color: #666;
  }
  
  .loading-container {
    padding: 20px;
  }
  
  .product-card {
    margin-bottom: 20px;
    transition: transform 0.3s;
  }
  
  .product-card:hover {
    transform: translateY(-5px);
  }
  
  .product-image {
    cursor: pointer;
    overflow: hidden;
  }
  
  .image-error {
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5;
    color: #999;
  }
  
  .product-name {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 8px;
    cursor: pointer;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .product-name:hover {
    color: #409eff;
  }
  
  .product-brand {
    font-size: 12px;
    color: #999;
    margin-bottom: 8px;
  }
  
  .product-price {
    margin-bottom: 12px;
  }
  
  .current-price {
    font-size: 18px;
    color: #f56c6c;
    font-weight: bold;
  }
  
  .original-price {
    font-size: 14px;
    color: #999;
    text-decoration: line-through;
    margin-left: 8px;
  }
  
  .product-actions {
    display: flex;
    justify-content: space-between;
  }
  
  .pagination {
    margin-top: 20px;
    text-align: center;
  }
  
  .empty-result {
    padding: 50px 0;
  }
  </style>